const Base = require('./base.js');

module.exports = class extends Base {
  async listAction() {
    // const typeId = this.get('typeId');

    const list = await this.model('attention')
      .field(['c.*', 'user.nickname', 'g.avatar', 'g.gender'])
      .alias('c')
      .join({
        table: 'user',
        join: 'left',
        as: 'g',
        on: ['c.value_id', 'g.id']
      })
      .where({ user_id: this.getLoginUserId(), is_attention: 1 })
      .page(this.get('page'))
      .countSelect();

    return this.success(list);
  }

  async addordeleteAction() {
    const typeId = this.post('typeId');
    const valueId = this.post('valueId');

    const attention = await this.model('attention')
      .where({
        type_id: typeId,
        value_id: valueId,
        user_id: this.getLoginUserId(),
        is_attention: 1
      })
      .find();
    let attentionRes = null;
    let handleType = 'add';
    if (think.isEmpty(attention)) {
      // 添加收藏
      attentionRes = await this.model('attention').add({
        type_id: typeId,
        value_id: valueId,
        user_id: this.getLoginUserId(),
        is_attention: 1,
        add_time: parseInt(new Date().getTime() / 1000)
      });
    } else {
      // 取消收藏
      attentionRes = await this.model('attention')
        .where({ id: attention.id })
        .delete();
      handleType = 'delete';
    }

    if (attentionRes > 0) {
      return this.success({ type: handleType });
    }

    return this.fail('操作失败');
  }
};
